//引入express模块
const express = require('express');
//引入pool.js连接池
const pool = require('../pool.js');
//创建路由器对象
const r = express.Router();
//http://127.0.0.1:8080/user
//添加路由用户注册(post  /)    注册用户
r.post('/',(req,res,next)=>{
    //获取post请求的数据
    let obj = req.body;
    console.log(obj);
    //验证各项数据是否为空
    if(!obj.uname){
        res.send({code:401,msg:'unmae不能为空'});
        return;
    }
    if(!obj.upwd){
        res.send({code:406,msg:'upwd不能为空'});
        return;
    }
    if(!obj.phone){
        res.send({code:402,msg:'phone不能为空'});
        return;
    }
    if(!obj.sex){
        res.send({code:403,msg:'sex不能为空'});
        return;
    }
    if(!obj.user_name){
        res.send({code:404,msg:'user_name不能为空'});
    }
    //验证手机号码是否为空
    if( !(/^1[3-9]\d{9}$/.test(obj.phone)) ){
        res.send({code:301,msg:'手机号码格式不正确'});
        return;
    }
    //执行sql语句命令，将获取的数据插入到数据表scp_user中
     pool.query('insert into scp_user set ?',[obj],(err,result)=>{
         if(err){
             next(err);
             return;
         };
         console.log(result);
         res.send({code:200,msg:'注册成功'});
    });
});


//2.添加用户登录的接口(post   /login)
r.post('/login',(req,res,next)=>{
        //获取传达的参数
        let obj = req.body;
        console.log(obj);
        //判断各项数据是否为空
        if(!obj.uname){
            res.send({code:401,msg:'用户名不能为空'});
            return;
        }
        if(!obj.upwd){
             res.send({code:404,msg:'密码不能为空'});
            return;
        }
        //执行sql命令
        pool.query('select * from scp_user where uname=? and upwd=?',[obj.uname,obj.upwd],(err,result)=>{
            if(err){
                next(err);
                return;
            }
            console.log(result);
            if(result.length===0){
                res.send({code:201,msg:'登录失败'});
            }else{
                res.send({code:200,msg:'登录成功'});
            }
        });
});
//删除接口
r.delete('/del/:uid',(req,res,next)=>{
        //获取id的值
        let obj = req.params;
        console.log(obj);
        pool.query('delete  from scp_user where uid=?',[obj.uid],(err,result)=>{
            if(err){
                next(err);
                return;
            }
            console.log(result);
            if(result.affectedRows===0){
                res.send({code:404,msg:'删除失败'});
                return;
            }else{
                res.send({code:200,msg:'删除成功'});
            }
        })
})

//导出路由器对象让app.js获取
module.exports = r;